package org.example.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.example.dto.RoomData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 对于房间的操作Service
 *
 * @Author 刘新
 * @Date 2023/10/30 16:04
 */
@Service
public class RoomService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加入房间
     *
     * @param userId 用户id
     * @param roomId 房间id
     * @return
     */
    public String joinRoom(Long userId, Long roomId) {
        String key = "roomID:" + roomId;
        // 判断是否有这个房间
        boolean keyExists = redisTemplate.hasKey(key);
        if (!keyExists) {
            throw new RuntimeException("房间不存在，是否要创建新房间？");
        }
        // 获取房间数据
        Object obj = redisTemplate.opsForValue().get(key);
        RoomData roomData = JSONArray.parseObject(obj.toString(), RoomData.class);
        // 房间最大人数
        Integer roomMaxSize = roomData.getMaxSize();
        // 房间当前用户数据
        List<Long> roomPeopleList = roomData.getRoomPeopleList();
        // 判断人数
        if (roomPeopleList.size() + 1 > roomMaxSize) {
            throw new RuntimeException("房间人数已满，是否要创建新房间？");
        } else {
            roomPeopleList.add(userId);
            roomData.setRoomPeopleList(roomPeopleList);
            String jsonString = JSONObject.toJSONString(roomData);
            redisTemplate.opsForValue().set(key, jsonString);
        }
        return "";
    }


    /**
     * 退出房间
     *
     * @param userId 用户id
     * @param roomId 房间id
     * @return
     */
    public String quitRoom(Long userId, Long roomId) {
        String key = "roomID:" + roomId;
        // 判断是否有这个房间
        boolean keyExists = redisTemplate.hasKey(key);
        if (keyExists) {
            // 获取房间数据
            Object obj = redisTemplate.opsForValue().get(key);
            RoomData roomData = JSONArray.parseObject(obj.toString(), RoomData.class);
            // 房间当前用户数据
            List<Long> roomPeopleList = roomData.getRoomPeopleList();
            // 房间有剩余人员，退出房间
            if (null != roomPeopleList && roomPeopleList.size() > 0) {
                // 判断用户是否在当前房间内
                boolean contains = roomPeopleList.contains(userId);
                if (contains) {
                    // 退出房间
                    roomPeopleList.remove(userId);
                    roomData.setRoomPeopleList(roomPeopleList);
                    String jsonString = JSONObject.toJSONString(roomData);
                    redisTemplate.opsForValue().set(key, jsonString);
                } else {
                    throw new RuntimeException("用户不在房间内");
                }
            } else {
                // 房间无剩余人员，则10秒后删除房间
                redisTemplate.expire(roomId.toString(), 10, TimeUnit.SECONDS);
            }
        }
        return "";
    }


    /**
     * 更新房间对战数据
     *
     * @param roomData
     * @return
     */
    public String updateBattleDataByRoom(RoomData roomData) {
        Integer[][] data = roomData.getData();
        String key = "roomID:" + roomData.getRoomId();

        // 判断是否有这个房间
        boolean keyExists = redisTemplate.hasKey(key);
        if (!keyExists) {
            throw new RuntimeException("房间不存在，是否要创建新房间？");
        }
        if (keyExists) {
            // 获取房间数据
            Object obj = redisTemplate.opsForValue().get(key);
            RoomData dto = JSONArray.parseObject(obj.toString(), RoomData.class);
            // 更新对战数据
            dto.setData(data);
            String jsonString = JSONObject.toJSONString(data);
            redisTemplate.opsForValue().set(key, jsonString);
        }
        return "";
    }


    /**
     * 获取房间数据
     *
     * @param roomId 房间id
     * @return
     */
    public RoomData getRoomData(Long roomId) {
        String key = "roomID:" + roomId;
        // 获取房间数据
        Object obj = redisTemplate.opsForValue().get(key);
        RoomData dto = JSONArray.parseObject(obj.toString(), RoomData.class);
        return dto;
    }
}
